package com.shse.login.web.controller;

import com.shse.login.meta.User;
import com.shse.login.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

/**
 * Created by shse on 3/13/2016.
 */
@Controller
public class HomeController {

    @Resource
    private UserService userService;

    //对应/api/login地址的get请求，提供登陆界面
    @RequestMapping(value = "/login" , method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    //对应/api/login地址的post请求，处理登陆逻辑
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public String login(@RequestParam("username") String userName,
                        @RequestParam("password") String userPassword,
                        HttpSession session,
                        ModelMap map){
        //利用表单传入参数进行用户获取操作，
        User user = userService.getUser(userName, userPassword);
        if(user==null){
            map.put("error", "用户名或密码错误");
            return "login";
        }else{
            //登陆成功则设置session
            session.setAttribute("user", user);

            //获得重定向路径
            String path = "/api/user/" + user.getUserId();

            //重定向至所登陆用户的欢迎界面
            return "redirect:" + path;
        }
    }

    //用户查看界面，可以通过userId查看指定用户
    @RequestMapping("/user/{userId}")
    public String user(@PathVariable("userId") Integer userId,
                       ModelMap map,
                       HttpSession session){

        //从session中尝试获取user
        User user = (User) session.getAttribute("user");

        //如果session中没有user或者user的id与当前要访问的用户id不同，则提示未登陆
        if (user==null || user.getUserId()!=userId){
            map.put("error", "用户未登录");
            return "error";
        }

        //如果session中user存在且是要访问的用户，则展示欢迎用户界面
        map.put("user", user);
        return "user";
    }
}
